package Yanxin.atguigu.yx.util;

import Yanxin.atguigu.yx.common.Constant;
import com.alibaba.druid.pool.DruidPooledConnection;
import org.apache.commons.beanutils.BeanUtils;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class JdbcUtil {

    //建立与phoenix的连接
    public static Connection getPhoenixConnection(){
        String driver = Constant.PHOENIX_DRIVER;

        String url = Constant.PHOENIX_URL;
        
        return getJdbcConnection(driver,url,null,null);
    }


    //jdbc连接器
    public static Connection getJdbcConnection(String driver, String url, String user, String password) {

        //加载驱动
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            throw new RuntimeException("你提供的驱动类有误，请检查导入的数据库连接器是否正确"+ driver);
        }

        //进行连接
        try {
            return DriverManager.getConnection(url, user, password);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("你提供的url, user, password有误，请检查" + "url: "+ url+ "user: " + user +"password: " + password);
        }

    }


    public static void closePhoenixConnection(Connection connection){

        if (connection!=null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }


    public static <T>List<T> queryList(DruidPooledConnection conn, String sql, String[] args, Class<T> tClass) {

        ArrayList<T> result = new ArrayList<>();

        try {

            PreparedStatement ps = conn.prepareStatement(sql);
            //todo 给占位符赋值
            for (int i = 0; args!=null && i < args.length ; i++) {

                //占位符从第一开始，args数组冲0开始
                ps.setObject(i+1,args[i]);
            }

            //获取结果集，并且获取列的元数据,获取出列的数量
            ResultSet resultSet = ps.executeQuery();
            ResultSetMetaData metaData = resultSet.getMetaData();
            int columnCount = metaData.getColumnCount();

            //遍历结果集,将每一个行查询的结果封装成一个对象，并且将对象添加到最前面创建的最终结果result
            while (resultSet.next()){

                //每一行的结果集封装成一个对象，通过反射获取对象
                T t = tClass.newInstance();

                //列从第1个开始
                for (int i = 1; i <=columnCount ; i++) {

                    String columnName = metaData.getColumnLabel(i); //拿到列名
                    Object value = resultSet.getObject(i); //拿到列对应的值

                    BeanUtils.setProperty(t,columnName,value);
                }

                result.add(t);

            }

            ps.close();


        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }
}
